<!-- 上传文件和详情 -->
<template>
  <div class="app-container">
    <Edialog
      :outershow="outershow"
      :title="title"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="type == 'upload' ? true : false"
      :width="'60%'"
    >
      <el-form
        inline
        ref="form"
        :model="form"
        v-if="type == 'upload'"
        label-width="90px"
      >
        <el-form-item label="文件上传" prop="excelJson" style="width: 48%">
          <!-- <el-input v-model="form.name" /> -->
          <input
            v-if="outershow"
            :loading="loading"
            type="file"
            class="choose"
            @change="loadExcelFile"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
          />
        </el-form-item>
        <el-form-item label="标题行" prop="titleRow" style="width: 48%">
          <el-input v-model="form.titleRow" />
        </el-form-item>
        <el-form-item label="表头所在行" prop="headRow" style="width: 48%">
          <el-input v-model="form.headRow"> </el-input>
        </el-form-item>
        <el-form-item label="表头所在列" prop="headCol" style="width: 48%">
          <el-input v-model="form.headCol" style="width: 90%" />
          <el-tooltip
            class="item"
            effect="dark"
            content="多行时用“,”隔开,比如'B,C'"
            placement="top"
          >
            <i style="margin-left: 10px" class="el-icon-question"></i>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <div
        v-else-if="type == 'detail'"
        style="margin-bottom: 10px"
        v-loading="formLoading"
      >
        <el-descriptions :column="4">
          <el-descriptions-item label="模板编码">{{
            detailform.templateCode
          }}</el-descriptions-item>

          <el-descriptions-item label="模板名称">{{
            detailform.templateName
          }}</el-descriptions-item>
          <el-descriptions-item label="表头所在行">{{
            detailform.headRow
          }}</el-descriptions-item>
          <el-descriptions-item label="表头所在列">{{
            detailform.headCol
          }}</el-descriptions-item>
          <el-descriptions-item label="科目数量">{{
            detailform.subjectNum
          }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{
            detailform.crMem
          }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            detailform.crTime
          }}</el-descriptions-item>
        </el-descriptions>
        <el-divider></el-divider>
        <h3 style="margin: 0" v-if="showExcel">
          模板预览
          <!-- 导出按钮 -->
          <el-button
            type="text"
            size="mini"
            style="margin: 10px 0"
            @click="exportExcel"
            >文件下载</el-button
          >
        </h3>
      </div>
      <!-- 只能预览 -->
      <SpreadSheet
        v-if="outershow && showExcel"
        style="height: 50vh; width: 100%"
        ref="Sheet"
        :SheetName="SheetName"
        :File="file"
        :Headers="headers"
        :ColumnWidth="200"
        :Records="records"
        :onlyRead="type == 'detail' ? true : true"
        @loaded="loaded"
      ></SpreadSheet>
    </Edialog>
  </div>
</template>

<script>
import {
  setCellEditable,
  updateRowAttributes,
  updateColumnAttributes,
} from "@/utils/spreadsheet.js";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import Edialog from "@/components/Edialog";
import { postUploadFilePrivate } from "@/api/management/user";
import { getFilePrivate } from "@/api/public";
import { saveWithFileApi, BsTemplateByIdApi } from "@/api/templateManage";
import { exportExcelFn } from "@/utils/publicReq";
export default {
  data() {
    return {
      formLoading: false,
      loading: false,
      SheetName: "Sheet1",
      type: "upload",
      templateType: [
        {
          value: "1",
          label: "类型1",
        },
        {
          value: "2",
          label: "类型2",
        },
      ],
      outershow: false,
      title: "上传文件",
      detailform: {
        templateCode: "",
        templateName: "",
        subjectNum: "",
        crMem: "",
        crTime: "",
      },
      form: {
        titleRow: "",
        headRow: "",
        headCol: "",
        excelJson: null,
        fileId: "",
        templateCode: "",
        templateName: "",
        remarks: "",
        id: "",
      },
      file: null,
      ColumnCount: 30,
      RowCount: 100,
      headers: [],
      records: [],
      DataSource: [],
      //为了在无文件时隐藏预览表格
      showExcel: false,
    };
  },
  components: {
    Edialog,
    SpreadSheet,
  },
  methods: {
    loaded(data) {
      setTimeout(() => {
        if (data) {
          // setCellEditable(data[0], 1, 0, false);
          // xs.reRender();
          this.form.excelJson = JSON.stringify(data);
          console.log("loaded", data);
        }
      });
    },
    //导出
    exportExcel() {
      // this.$refs.Sheet.exportExcel(this.fileName || "模板名称");
      exportExcelFn(this.detailform.fileId, this.detailform.templateName);
    },
    //上传文件
    async loadExcelFile(e) {
      if (e.target.files[0]) {
        console.log(e.target.files[0]);
        this.loading = true;
        let FD = new FormData();
        FD.append(`file`, e.target.files[0]);
        let data = await postUploadFilePrivate(FD);

        this.showExcel = true;
        this.$nextTick(() => {
          this.file = e.target.files[0];
        });
        if (data.code == 0 && data.data.bcode == 0) {
          this.form.fileId = data.data.bdata;
        }
        this.loading = false;
      }
    },
    //外部打开弹窗
    async openFn(type, scope) {
      if (type === "detail") {
        this.title = "详情";
      } else {
        this.title = "上传文件";
      }
      this.showExcel = false;
      this.formLoading = true;
      this.file = null;
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
      this.type = type;
      this.outershow = true;
      let detailData = await BsTemplateByIdApi(scope.id);
      if (
        detailData.data &&
        detailData.data.bdata &&
        detailData.data.bcode == 0
      ) {
        if (type === "detail") {
          this.detailform = detailData.data.bdata;

          if (scope.fileId) {
            this.showExcel = true;
            setTimeout(() => {
              this.$nextTick(() => {
                this.$refs.Sheet.loadData(JSON.parse(scope.excelJson) || []);
              });
            });
          } else {
            this.showExcel = false;
          }
        } else if (type === "upload") {
          this.form.templateCode = detailData.data.bdata.templateCode;
          this.form.templateName = detailData.data.bdata.templateName;
          this.form.id = scope.id;
        }
      }
      console.log("detailData", this.detailform);
      this.formLoading = false;
    },
    async saveFn() {
      // xsRows.eachCells(this.form.headRow, (ci, cell) => {
      //   console.log("ci, cell1", ci, cell);
      //   cell.editable = false;
      // });
      console.log("this.form", this.form.excelJson);

      if (!this.form.excelJson) {
        this.$message.error("请上传有效文件");
      }
      let x = JSON.parse(this.form.excelJson);
      updateRowAttributes(x, this.form.headRow, {
        editable: false,
        isTitle: true,
      });
      updateColumnAttributes(x, this.form.headCol, {
        editable: false,
        isTitle: true,
      });
      this.form.excelJson = JSON.stringify(x);
      // console.log("this.form.excelJson", this.form.excelJson);
      // return;
      // xs.reRender();
      setTimeout(() => {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            console.log("this.form", JSON.parse(this.form.excelJson));
            let res = await saveWithFileApi({
              ...this.form,
            });
            if (res.code == 0 && res.data.bcode == 0) {
              this.$message.success("上传成功");
            }
            this.closeFn();
            this.$emit("refreshFn");
          }
        });
      });
    },
    closeFn() {
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      this.outershow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.el-form-item {
  width: 50%;
}
::v-deep .el-form-item__content {
  width: 80%;
}
.choose::-webkit-file-upload-button {
  color: white;
  display: inline-block;
  background: #409eff;
  border: none;
  padding: 12px 20px;
  width: 100px;
  height: 40px;
  border-radius: 3px;
  white-space: nowrap;
  cursor: pointer;
  font-size: 10pt;
}
</style>
